package com.example.transactionhintassistant.utils;

import com.alibaba.druid.util.StringUtils;
import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
public class JwtHelper {
    @Value("${jwt.token.tokenExpiration}")
    private  long tokenExpiration; //有效时间,单位毫秒 1000毫秒 == 1秒
    @Value("${jwt.token.tokenSignKey}")
    private  String tokenSignKey;  //当前程序签名秘钥

    //生成token字符串
    public  String createToken(int userId) {
        return Jwts.builder()

                .setSubject("YYGH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration*1000*60)) //单位分钟
                .claim("userId", userId)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    //从token字符串获取userid
    public  Integer getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (Integer)claims.get("userId");
    }



    //判断token是否有效
    public  boolean isExpiration(String token){
        try {
            //没有过期，有效，返回false
            return Jwts.parser()
                    .setSigningKey(tokenSignKey)
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration().before(new Date());
        }catch(Exception e) {
            //过期出现异常，返回true
            return true;
        }
    }
}
